#include"data_global.h"
#include "sem.h"

extern struct env_info b;
struct env_info *shm_buf = NULL;
int shmid;
int semid;
extern prodcons_t init;
int init_shm(void)
{
	key_t key;
	key = ftok("/app", 'i');
	if((shmid = shmget(key, N, 0666 )) == -1)
	{
		perror("shmget");
		exit(1);
	}

	if((shm_buf = (struct env_info*)shmat(shmid, NULL, 0)) == (void*)-1)
	{
		perror("shmat");
		exit(1);
	}
	if((semid  = semget(key, 1, 0666)) < 0)
	{
		perror("semget");
		exit(1);
	}

}

int delete_shm(void)
{
	if(shmdt(shmaddr) == -1)
	{
		perror("shmdt");
		return -1;
	}

	if(shmctl(shmid,IPC_RMID,NULL) == -1)
	{
		perror("shmctl");
		return -1;
	}

	return 0;
}

void *handler_refresh(void *data)
{
	pthread_mutex_lock(&mutex);
	while(flag != 1)
	{
		pthread_cond_wait(&cond,&mutex);
	}
	sem_p (semid, 0);
	memcpy(shm_buf, &b, sizeof(struct env_info));
	sem_v (semid, 0);
	flag = 0;
	pthread_mutex_unlock(&mutex);
	pthread_cond_broadcast(&cond);
	return NULL;
}
